package com.chinamsp.codegen.convert.db;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;

import com.mysql.cj.core.MysqlType;

/**
 * db  工具
 * @author shifenghu
 *
 */
public class DbCodeGenUtils {

	
	/**
	 * 将字段转换成属性
	 * @param field
	 * @return
	 */
	public static String fieldToProperty(String field) {
		Assert.notNull(field, "要转换的字段/表名不能为空");
		Matcher matcher = Pattern.compile(FIELD_TO_PROPERTY_PATTERN).matcher(field.toLowerCase());
		StringBuffer sb = new StringBuffer();
		// 逐个替换
		while(matcher.find()){
			matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
		}
		// 最后一段或者失败的字段直接添加
		matcher.appendTail(sb);
		return sb.toString();
	}
	
	/**
	 * 包转换成文件路径
	 * @param packageName
	 * @return
	 */
	public static String packageToPath(String packageName) {
		Assert.notNull(packageName, "转换的包名不存在");
		return packageName.replaceAll(PACKAGE_SPEARATOR, "\\" + File.separator);
	}
	
	/**
	 * 获取 get name
	 * @param proName
	 * @return
	 */
	public static String genGetterName(String proName) {
		return GETTER_PREFIX + proName.substring(0, 1).toUpperCase() + proName.substring(1);
	}
	
	/**
	 * 首字母大写
	 * @param str
	 * @return
	 */
	public static String ftUpcase(String str) {
		return StringUtils.isBlank(str) ? str : str.substring(0, 1).toUpperCase() + str.substring(1);
	}
	
	/**
	 * 数据库类型转换成 java 类型
	 * @param dbType
	 * @return
	 */
	public static Class<?> dbTypeCovertJavaType(String dbType){
		try {
			return Class.forName(MysqlType.getByName(dbType).getClassName());
		} catch (ClassNotFoundException e) {
			throw new IllegalArgumentException(e);
		}
	}
	
	/**
	 * 获取 set name
	 * @param proName
	 * @return
	 */
	public static String genSetterName(String proName) {
		return SETTER_PREFX + proName.substring(0, 1).toUpperCase() + proName.substring(1);
	}
	
	/**
	 * 字段转属性正则
	 */
	private static final String FIELD_TO_PROPERTY_PATTERN = "\\_([^_])";
	
	
	private static final String PACKAGE_SPEARATOR = "\\.";
	
	private static final String GETTER_PREFIX  = "get";
	
	private static final String SETTER_PREFX = "set";
}
